package cn.lsh.cas;

import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.lsh.pojo.Module;
import cn.lsh.pojo.Role;
import cn.lsh.pojo.User;
import cn.lsh.service.UserService;

@Slf4j
public class ShiroCasRealm extends CasRealm{

	@Autowired
	private UserService userService;
	
	@PostConstruct//初始化bean之前执行的操作
	protected void initProperty(){
		setCasServerUrlPrefix(ShiroCasConfiguration.casServerUrlPrefix);
		//客户端回调地址
		setCasService(ShiroCasConfiguration.shiroServerUrlPrefix+ShiroCasConfiguration.casFilterUrlPattern);
	}
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		AuthenticationInfo auth=super.doGetAuthenticationInfo(token);
		String account=(String)auth.getPrincipals().getPrimaryPrincipal();
		SecurityUtils.getSubject().getSession().setAttribute("no", account);
		log.info("登录认证,account:{}",account);
		return auth;
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		// TODO Auto-generated method stub
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		String username=(String) super.getAvailablePrincipal(principal);
		User user=userService.findUserByUserName(username);
		for(Role role:user.getRoles()){
			authorizationInfo.addRole(role.getRname());
			for(Module perm : role.getModules()){
				authorizationInfo.addStringPermission(perm.getMname());
			}
		}
		return authorizationInfo;
	}
}
